﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Report
{
    public class CSVGenerator
    {
        public void ExportToCSVFile(IList<IItem> items, IEnumerable<string> headers,string fileName)
        {
            using (var streamWriter = new StreamWriter(fileName, true,Encoding.UTF8))
            {
                WriteHeaderLine(streamWriter, headers);
                streamWriter.WriteLine();
                WriteContents(streamWriter, items);
                streamWriter.Flush();
            }
        
        }

        private void WriteContents(StreamWriter writer, IList<IItem> items)
        {
            foreach (var rItem in items)
            {
                WriteValue(writer, rItem.FirstLevel);
                WriteValue(writer,rItem.SecondLevel);
                WriteValue(writer,rItem.AddDate == DateTime.MinValue? string.Empty: rItem.AddDate.ToString("yyyy/MM/dd"));
                WriteValue(writer,rItem.ContentSummary);
                WriteValue(writer, rItem.Income.ToString());
                WriteValue(writer, rItem.Cost.ToString());
                WriteValue(writer,rItem.ExistingIncome.ToString());
                WriteValue(writer, rItem.ShouldHaveIncome.ToString());
                WriteValue(writer, rItem.Borrow.ToString());
                WriteValue(writer, rItem.Lent.ToString());
                WriteValue(writer, rItem.Comment);
                writer.WriteLine();

            }
        }
        private void WriteValue(StreamWriter writer, String value)
        {
            writer.Write("\"");
            writer.Write((value?? string.Empty).Replace("\"", "\"\""));
            writer.Write("\",");
        }

        private void WriteHeaderLine(StreamWriter streamWriter, IEnumerable<string> headers)
        {
            foreach (var header in headers)
            {
                WriteValue(streamWriter, header);
            }
        }
    }
}